package com.rongc.client.freight.business.mine.view.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Environment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.rongc.client.core.exception.RegexException;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.StringUtils;
import com.rongc.client.freight.R;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.view.adapter.RecyclerAuthAdapter;
import com.rongc.client.freight.base.view.adapter.RecyclerBaseAdapter;
import com.rongc.client.freight.business.mine.model.CarDic;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by ccqx on 2017/6/28.
 */

public class CarPhotoActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks, View.OnClickListener{
    @Bind(R.id.recycler)
    RecyclerView mRecyclerView;

    RecyclerAuthAdapter authAdapter;
    List<HashMap<String,String>> datas;
    private ArrayList<String> netPhotos = new ArrayList<>();
    ArrayList<String> filenames = new ArrayList<>();


    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;

    @OnClick({R.id.btn_sub,R.id.tv_protocol})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_sub:
                try{
                    netPhotos.clear();
                    filenames.clear();
                    netPhotos.add(datas.get(0).get("image"));
                    netPhotos.add(datas.get(1).get("image"));
                    netPhotos.add(datas.get(2).get("image"));
                    netPhotos.add(datas.get(3).get("image"));
                    filenames.add(datas.get(0).get("filename"));
                    filenames.add(datas.get(1).get("filename"));
                    filenames.add(datas.get(2).get("filename"));
                    filenames.add(datas.get(3).get("filename"));
                    prepare();

                    Intent intent = new Intent();
                    intent.putStringArrayListExtra("names",filenames);
                    intent.putStringArrayListExtra("photos",netPhotos);
                    setResult(RESULT_OK,intent);
                    finish();
                }catch (RegexException e){
                    ActivityUtils.toast(e.getMessage());
                }

                break;
            case R.id.tv_protocol:
                ActivityUtils.startActivity(this, ProblemActivity.class);
                break;
        }
    }

    void prepare() throws RegexException {
        for (String path :netPhotos) {
            if(StringUtils.isEmpty(path))
                throw new RegexException("请上传所有图片");
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == StringUtils.parseInt(CarDic.PhotoType.DRIVING_TYPE)) {
            String path = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            datas.get(0).put("image",path);
        }else if (resultCode == RESULT_OK && requestCode == StringUtils.parseInt(CarDic.PhotoType.HEAD_TYPE)) {
            String path = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            datas.get(1).put("image",path);
        }else if (resultCode == RESULT_OK && requestCode == StringUtils.parseInt(CarDic.PhotoType.BODY_TYPE)) {
            String path = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            datas.get(2).put("image",path);
        }else if (resultCode == RESULT_OK && requestCode == StringUtils.parseInt(CarDic.PhotoType.TAIL_TYPE)) {
            String path = BGAPhotoPickerActivity.getSelectedImages(data).get(0);
            datas.get(3).put("image",path);
        }

        authAdapter.notifyDataSetChanged();
    }


    @Override
    public void initParams() {
        netPhotos = getIntent().getStringArrayListExtra("photos");
    }

    @Override
    public void initView() {
        datas= new ArrayList<>();

        initToolbar(R.string.car_create_photo);
        HashMap<String,String> data = new HashMap<>();
        data.put("name","驾驶证照");  // 驾驶证照
        data.put("id", CarDic.PhotoType.DRIVING_TYPE);
        data.put("filename", "img");
        data.put("image","");
        datas.add(data);
        data = new HashMap<>();
        data.put("name","车头照");  // 车头照
        data.put("id",CarDic.PhotoType.HEAD_TYPE);
        data.put("filename", "img2");
        data.put("image","");
        datas.add(data);
        data = new HashMap<>();
        data.put("name","车身照");  // 车身照
        data.put("id", CarDic.PhotoType.BODY_TYPE);
        data.put("filename", "img3");
        data.put("image","");
        datas.add(data);
        data = new HashMap<>();
        data.put("name","车尾照");  // 车尾照
        data.put("id",CarDic.PhotoType.TAIL_TYPE);
        data.put("filename", "img4");
        data.put("image","");
        datas.add(data);


        if(netPhotos != null && netPhotos.size() > 0)
            for (int i = 0;i<netPhotos.size();i++){
                datas.get(i).put("image",netPhotos.get(i));
            }


        authAdapter = new RecyclerAuthAdapter(this,datas);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(authAdapter);

        authAdapter.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener<HashMap<String, String>>() {
            @Override
            public void onItemClick(View view, int position, HashMap<String, String> data) {
                req = StringUtils.parseInt(data.get("id"));
                choicePhotoWrapper();
            }
        });
    }
    int req;
    @Override
    public int getLayoutId() {
        return R.layout.activity_sys_auth;
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "FreDownload");

            startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 1, null), req);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }
}
